#include <iostream>
#include <QtWidgets>
#include <QtSql>
#include "commoditywindow.h"
#include "mainwindow.h"

using namespace std;

void initdb() {
    if (!QSqlDatabase::drivers().contains("QSQLITE"))
         std::cerr << "This demo needs the SQLITE driver" << std::endl;
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("../demo.sqlite");
    if (!db.open()) {
        cout << db.lastError().text().toStdString();
        return;
    }
    QSqlQuery query(db);

    if(!QFile::exists("../demo.sqlite")) {
        std::cout << "demo.sqlite not exits" << std::endl;
        query.exec("CREATE TABLE wms_commodity\
                    (\
                      id INTEGER PRIMARY KEY NOT NULL,\
                      name VARCHAR(64) NOT NULL,\
                      type_number VARCHAR(128),\
                      unit VARCHAR(64),\
                      price DECIMAL \
                    );");
        query.exec("INSERT INTO wms_commodity (name, type_number, unit, price) VALUES ('Apple', '000','kilo', '6.72');");
        query.exec("INSERT INTO wms_commodity (name, type_number, unit, price) VALUES ('Orange', '034','kilo', '3.99');");
    }
    if(!query.exec("select * from wms_commodity;")) {
        cout << query.lastError().text().toStdString();
    }
    int n = query.record().count();
    std::cout << n << std::endl;
    while(query.next()) {
        for(int i=0; i<n; ++i) {
              std::cout << query.value(i).toString().toStdString() << "\t";
        }
        std::cout << std::endl;
    }
}

int main(int argc, char *argv[]) {
    initdb();
    QApplication app(argc, argv);
//    CommodityWindow cwindow;
//    cwindow.show();
    MainWindow mwindow;
    mwindow.show();
    return app.exec();

}

